package com.zr.servlet;

import com.alibaba.fastjson.JSON;
import com.zr.service.UserService;
import com.zr.service.impl.UserServiceImpl;
import com.zr.utils.ResultObj;
import com.zr.vo.User;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/user/login")
public class UserLoginServlet extends HttpServlet {

    private UserService userService = new UserServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        String value = req.getReader().readLine();
        User user = JSON.parseObject(value, User.class);
        User loginUser = userService.login(user.getUserId(), user.getPassword());
        PrintWriter out = resp.getWriter();
        ResultObj resultObj = null;
        if(loginUser != null){
            resultObj  = ResultObj.success(200, "登录成功", loginUser);
        }else {
            resultObj  = ResultObj.fail(200, "账号或密码错误", null);
        }
        out.write(JSON.toJSONString(resultObj));
        out.flush();
    }
}
